<?php
namespace App\Http\Controllers\Manage\AD;

use App\Http\Controllers\Manage\CommonController;
use App\Model\AD\AdCategory;
use App\Model\AD\Ad;

class AdController extends CommonController
{
    /**
     * 广告列表页
     * @return mixed
     */
    public function index()
    {
        $field = [
            'id' => 'ID',
            'name' => '标题',
            'link' => '连接',
            'category_id' => '广告位'
        ];
        $viewData = [];
        $viewData['title'] = '商城广告管理';
        $viewData['nav'] = $this->navTab('ad', 'main');
        # 列表查询字段
        $viewData['field'] = $field;
        # 列表取值范围替换
        $viewData['range'] = [
            'category_id' => $this->getCategory()
        ];
        # 列表操作菜单
        $viewData['option_title'] = [
            'plus' => [
                'title' => '添加广告',
                'route' => route('manage.ad.resource.create')
            ]
        ];
        $page = $this->request->input('page', 1);
        # 行表操作菜单
        $viewData['option_row'] = [
            'edit' => [
                'title' => '修改',
                'route' => 'manage.ad.resource.edit',
                'param' =>   [
                    'page' => $page
                ]
            ],
            'trash' => [
                'title' => '删除',
                'route' => 'manage.ad.resource.destroy',
            ]
        ];
        # 页面模态对话框
        $viewData['option_modal'] = [
            'trash' => [
                'method' => 'DELETE',
                'title' => '删除记录',
                'msg' => '确定要删除广告吗'
            ]
        ];
        #列表数据
        $ad = new Ad;
        $viewData['list'] = $this->constraintSelect($ad, $field);
        # 渲染视图
        return view('manage.table', $viewData);
    }

    /**
     * 删除广告
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $result = Ad::where('id', $id)->delete();
        if ($result) {
            return redirect()->back()->with('success', '广告删除成功!');
        }
        return redirect()->back()->with('error', '广告删除失败!');
    }

    /**
     * 创建广告页面
     * @return mixed
     */
    public function create()
    {
        # 表单元素
        $param = [
            'name' => [
                'type' => 'text',
                'col' => '4',
                'name' => '标题',
            ],
            'category' => [
                'type' => 'select',
                'col' => '4',
                'name' => '广告位',
                'range' => $this->getCategory()
            ],
            'link' => [
                'type' => 'text',
                'col' => '12',
                'name' => '广告链接'
            ],
            'picture' => [
                'type' => 'file',
                'col' => '12',
                'name' => '广告图片',
                'accept' => 'image',
                'ratio' => '1',
            ]
        ];
        $viewData = [];
        $viewData['title'] = '添加广告';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.ad.resource.store');
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'return' => [
                'name' => '返回广告列表',
                'type' => 'button',
                'route' => route('manage.ad.resource.index')
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     * 创建广告操作
     * @return mixed
     */
    public function store()
    {
        if (!$this->request->has('name')) {
            return redirect()->back()->with('error', '请填写广告标题!');
        }
        $category= $this->request->input('category');
        $adCategory = AdCategory::find($category);
        if ($adCategory->total > 0) {
            $count = Ad::where('category_id', $category)->count();
            if ($count >= $adCategory->total) {
                return redirect()->back()->with('error', '当前广告位已到达最大限制!');
            }
        }
        else{
            return redirect()->back()->with('error', '当前广告位数量限制异常!');
        }
        if (!$this->request->hasFile('picture')) {
            return redirect()->back()->with('error', '请选择广告图!');
        }
        $picture = $this->request->file('picture');
        $file = $this->uploadImage($picture, 'ad');
        if (isset($file['error'])) {
            return redirect()->back()->with('error', $file['error']);
        }
        $ad = new Ad;
        $ad->name = $this->request->input('name');
        $ad->category_id = $category;
        $ad->link = $this->request->input('link');
        if (isset($file['file'])) {
            $ad->picture = $file['file']['name'];
        }
        if ($ad->save()) {
            return redirect()->route('manage.ad.resource.index')->with('success', '广告创建成功!');
        }
        return redirect()->back()->with('error', '广告创建失败!');
    }

    /**
     * 修改广告信息页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        # 查询记录数据
        $data = Ad::find($id);
        $picture = array();
        $picture[] = [
            'original' => '原始文件(' . $data->img_original . ')',
            'name' => $data->picture,
            'file' => $this->domain . $this->path['ad'] . $data->picture,
            'id' => $id,
        ];
        $picture = json_encode($picture);
        # 表单元素
        $param = [
            'name' => [
                'type' => 'text',
                'col' => '4',
                'name' => '标题',
                'value' => $data->name
            ],
            'category' => [
                'type' => 'select',
                'col' => '4',
                'name' => '广告位',
                'range' => $this->getCategory(),
                'value' => $data->category_id
            ],
            'link' => [
                'type' => 'text',
                'col' => '12',
                'name' => '广告链接',
                'value' => $data->link
            ],
            'picture' => [
                'type' => 'file',
                'col' => '12',
                'name' => '广告图片',
                'accept' => 'image',
                'value' => $picture
            ]
        ];
        $viewData = [];
        $viewData['title'] = '修改广告';
        $viewData['form'] = $this->form($param);
        $page = $this->request->input('page', 1);
        $viewData['form_url'] = route('manage.ad.resource.update', ['id' => $id, 'page' => $page]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'return' => [
                'name' => '返回广告列表',
                'type' => 'button',
                'route' => route('manage.ad.resource.index')
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     * 修改广告信息操作
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        if (!$this->request->has('name')) {
            return redirect()->back()->with('error', '请填写广告标题!');
        }
        $ad = Ad::find($id);
        $category = $this->request->input('category');
        # 获取当前广告位
        $adCategory = AdCategory::find($category);
        if ($adCategory->total < 1) {
            return redirect()->back()->with('error', '当前广告位最大限制异常!');
        }
        # 当前广告位广告总数
        $count = Ad::where('category_id', $category)->count();
        # 如果没有修改广告位置，只需要判断当前广告位是否溢出
        if ($category == $ad->category_id) {
            if ($count > $adCategory->total) {
                return redirect()->back()->with('error', '当前广告位已到达最大限制!');
            }
        }
        else{
            # 如果没有修改广告位置，需要判断当前广告位是否饱和
            if ($count >= $adCategory->total) {
                return redirect()->back()->with('error', '当前广告位已到达最大限制!');
            }
        }
        $ad->category_id = $category;
        if ($this->request->hasFile('picture')) {
            $picture = $this->request->file('picture');
            $file = $this->uploadImage($picture, 'ad');
            if (isset($file['file'])) {
                $ad->picture = $file['file']['name'];
            }
        }
        $ad->name = $this->request->input('name');
        $ad->link = $this->request->input('link');
        if (!$ad->save()) {
            return redirect()->back()->with('error', '广告修改失败!');
        }
        $page = $this->request->input('page', 1);
        $param = [
            'page' => $page
        ];
        return redirect()->route('manage.ad.resource.index', $param)->with('success', '广告修改成功!');
    }

    /**
     * 获取商品属性列表
     * @return mixed
     */
    private function getCategory()
    {
        $category = array();
        $result = AdCategory::get();
        foreach ($result as $key => $val) {
            $category[$val->id] = $val->name;
        }
        return $category;
    }
}
